import { useReducer, useRef } from "react";
import { useSafeDispatch } from "./useSafeDispatch";

/**
 * useState 增强版
 * @param initailValue 初始化状态
 * @returns
 */
export function useStatePlus<T>(initailValue: T) {
  const ref = useRef(initailValue);
  ref.current = initailValue;
  const [state, dispatch] = useReducer(
    (s: T, action: Partial<T>) => ({ ...s, ...action }),
    ref.current
  );
  const setState = useSafeDispatch(dispatch);
  return [state, setState] as const;
}
